import axios, { AxiosInstance, AxiosRequestConfig, AxiosError } from 'axios'
import type {
  HttpResponse,
  // 请求类型
  LoginRequest,
  RegisterRequest,
  SendCodeRequest,
  LoginWithCodeRequest,
  RegisterWithCodeRequest,
  ProfileCreateRequest,
  // 响应类型
  LoginResponse,
  RegisterResponse,
  SendCodeResponse,
  AuthResponse,
  ProfileListResponse,
  ProfileResponse,
  ProfileDeleteResponse,
  VideoListResponse,
  DouyinMainPageInfoResponse
} from '../../common/types/http-ipc'

class HttpService {
  private baseURL: string
  private timeout: number
  private client: AxiosInstance

  constructor() {
    // 使用 127.0.0.1 而不是 localhost，避免 IPv6 连接问题
    this.baseURL = 'http://127.0.0.1:8000'
    this.timeout = 30000 // 30秒超时
    
    // 创建 axios 实例
    this.client = axios.create({
      baseURL: this.baseURL,
      timeout: this.timeout,
      headers: {
        'Content-Type': 'application/json',
      },
    })

    // 请求拦截器
    this.client.interceptors.request.use(
      (config) => {
        console.log(`[HTTP] ${config.method?.toUpperCase()} ${config.url}`)
        return config
      },
      (error) => {
        console.error('[HTTP] Request error:', error)
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    this.client.interceptors.response.use(
      (response) => {
        console.log(`[HTTP] Response ${response.status} for ${response.config.url}`)
        return response
      },
      (error) => {
        console.error('[HTTP] Response error:', error.message)
        return Promise.reject(error)
      }
    )
  }

  // 设置认证令牌
  setAuthToken(token: string | null): void {
    if (token) {
      this.client.defaults.headers.common['Authorization'] = `Bearer ${token}`
    } else {
      delete this.client.defaults.headers.common['Authorization']
    }
  }

  // 通用请求方法
  async request(config: AxiosRequestConfig): Promise<HttpResponse> {
    try {
      const response = await this.client(config)
      
      return {
        success: true,
        data: response.data,
        status: response.status,
        headers: response.headers as Record<string, string>
      }
    } catch (error) {
      const axiosError = error as AxiosError
      console.error('[HTTP] Request failed:', axiosError.message)
      
      // 处理连接错误，提供更友好的错误信息
      let errorMessage = axiosError.message || '请求失败'
      if (axiosError.code === 'ECONNREFUSED') {
        errorMessage = '无法连接到后端服务器，请确保后端服务正在运行在 http://127.0.0.1:8000'
      } else if (axiosError.code === 'ETIMEDOUT') {
        errorMessage = '请求超时，请检查网络连接'
      }
      
      return {
        success: false,
        error: {
          code: axiosError.code || 'UNKNOWN_ERROR',
          message: errorMessage,
          details: axiosError.response?.data || null
        },
        status: axiosError.response?.status || 0,
        headers: (axiosError.response?.headers as Record<string, string>) || {}
      }
    }
  }

  // 类型安全的 API 调用方法
  async get(endpoint: string, params: Record<string, any> = {}): Promise<HttpResponse> {
    return this.request({
      method: 'GET',
      url: endpoint,
      params
    })
  }

  async post(endpoint: string, data: any = {}): Promise<HttpResponse> {
    return this.request({
      method: 'POST',
      url: endpoint,
      data
    })
  }

  async put(endpoint: string, data: any = {}): Promise<HttpResponse> {
    return this.request({
      method: 'PUT',
      url: endpoint,
      data
    })
  }

  async delete(endpoint: string): Promise<HttpResponse> {
    return this.request({
      method: 'DELETE',
      url: endpoint
    })
  }

  // 预定义的 API 方法
  async login(phone: string, password: string): Promise<HttpResponse<LoginResponse>> {
    return this.post('/api/auth/login', { phone, password })
  }

  async register(phone: string, password: string, name?: string): Promise<HttpResponse<RegisterResponse>> {
    return this.post('/api/auth/register', { phone, password, name })
  }

  async sendCode(phone: string, type: number): Promise<HttpResponse<SendCodeResponse>> {
    console.log('[HTTP] sendCode called:', { phone, type })
    const result = await this.post('/api/auth/send-code', { phone, type })
    console.log('[HTTP] sendCode result:', result)
    return result
  }

  async loginWithCode(phone: string, code: string): Promise<HttpResponse<AuthResponse>> {
    console.log('[HTTP] loginWithCode called:', { phone, code })
    const result = await this.post('/api/auth/login-with-code', { phone, code })
    console.log('[HTTP] loginWithCode result:', result)
    return result
  }

  async registerWithCode(phone: string, code: string): Promise<HttpResponse<AuthResponse>> {
    console.log('[HTTP] registerWithCode called:', { phone, code })
    const result = await this.post('/api/auth/register-with-code', { phone, code })
    console.log('[HTTP] registerWithCode result:', result)
    return result
  }

  // 主页管理方法（使用 homepage 命名，但后端 API 路径保持不变）
  async getHomePages(): Promise<HttpResponse<ProfileListResponse>> {
    const res = await this.get('/api/homepage')
    // 后端未实现该列表接口时可能返回 404，这里优雅降级为空列表，避免前端报错
    if (!res.success && res.status === 404) {
      return {
        success: true,
        data: { profiles: [] },
        status: 200,
        headers: res.headers || {}
      }
    }
    return res
  }

  async addHomePage(homepage: ProfileCreateRequest): Promise<HttpResponse<ProfileResponse>> {
    return this.post('/api/homepage', homepage)
  }

  async updateHomePage(id: string, updates: any): Promise<HttpResponse<ProfileResponse>> {
    return this.put(`/api/homepage/${id}`, updates)
  }

  async deleteHomePage(id: string): Promise<HttpResponse<void>> {
    return this.delete(`/api/homepage/${id}`)
  }

  // 保持向后兼容的别名（内部仍使用 profile 命名调用后端）
  async getProfiles(): Promise<HttpResponse<ProfileListResponse>> {
    return this.getHomePages()
  }

  async addProfile(profile: ProfileCreateRequest): Promise<HttpResponse<ProfileResponse>> {
    return this.addHomePage(profile)
  }

  async updateProfile(id: string, updates: any): Promise<HttpResponse<ProfileResponse>> {
    return this.updateHomePage(id, updates)
  }

  async deleteProfile(id: string): Promise<HttpResponse<void>> {
    return this.deleteHomePage(id)
  }

  async getVideos(profileId?: string): Promise<HttpResponse<VideoListResponse>> {
    const params = profileId ? { profileId } : {}
    return this.get('/api/videos', params)
  }

  async getDouyinMainPageInfo(url: string): Promise<HttpResponse<DouyinMainPageInfoResponse>> {
    return this.post('/api/douyin/main-page-info', { url })
  }
}

export default HttpService
